import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:zywz/bloc/listen/glod_bloc.dart';
import 'package:zywz/dialog/dialog1.dart';
import 'package:zywz/pages/auth/login_page.dart';
import 'package:zywz/pages/home/home_page.dart';
import 'package:zywz/pages/profile/profile_page.dart';
import 'package:zywz/pages/report/report_new_page.dart';
import 'package:zywz/api/net/report_page.dart';
import 'package:zywz/pages/services/services_page.dart';
import 'package:zywz/utils/AuthService.dart';
import 'package:zywz/utils/FixedCircleTabStyle.dart';
import 'SplashPage.dart';
import 'api/api_client.dart';
import 'bloc/auth/auth_bloc.dart';
import 'bloc/auth/auth_state.dart';
import 'bloc/home/home_bloc.dart';
import 'bloc/home/home_state.dart';
import 'bloc/home/homeother/home_btm_more_bloc.dart';
import 'bloc/profile/company_bloc.dart';
import 'bloc/report/report_bloc.dart';
import 'bloc/service/service_bloc.dart';
import 'generated/assets.dart';

// 定义路由配置
// final GoRouter _router = GoRouter(
//   routes: [
//     GoRoute(
//       path: '/',
//       builder: (context, state) => const SplashPage(),
//     ),
//     GoRoute(
//       path: '/login',
//       builder: (context, state) => const LoginPage(),
//     ),
//     GoRoute(
//       path: '/home',
//       builder: (context, state) => const MainPage(),
//     ),
//   ],
// );
// class HomeApp extends StatelessWidget {
//   const HomeApp({super.key});
//
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp.router(
//       title: '章鱼记账',
//       theme: ThemeData(
//         primarySwatch: Colors.blue,
//         scaffoldBackgroundColor: const Color(0xFFF4F7FF),
//         fontFamily: 'PingFang SC',
//       ),
//       routerConfig: _router,
//       debugShowCheckedModeBanner: false,
//     );
//   }
// }

// --- 主导航框架 ---
class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with SingleTickerProviderStateMixin {
  final PageController _pageController = PageController();
  int _selectedIndex = 0;
  int lastIndex = 0;

  // GoRoute(path: '/home', pageBuilder: (context, state) => const NoTransitionPage(child: HomePage())),
  // GoRoute(path: '/report', pageBuilder: (context, state) => const NoTransitionPage(child: ReportPage())),
  // // GoRoute(path: '/ai', pageBuilder: (context, state) => const NoTransitionPage(child: AiChatPage())),
  // GoRoute(path: '/services', pageBuilder: (context, state) => const NoTransitionPage(child: ServicesPage())),
  // GoRoute(path: '/profile', pageBuilder: (context, state) => const NoTransitionPage(child: ProfilePage())),

  // 定义四个主页面
  final List<Widget> _pages = [
    MultiBlocProvider(
      providers: [
        BlocProvider<HomeBtmMoreBloc>(
          create: (context) => HomeBtmMoreBloc(apiClient: ApiClient.instance),
        ),
      ],
      child: const HomePage(),
    ),
    // const ReportPage(),
    // const ReportsNewPage(),
    BlocProvider(
      create: (context) => ReportBloc(apiClient: ApiClient.instance),
      child: const ReportsNewPage(),
    ),

    ServicesPage(),

    // BlocProvider<CompanyBloc>(
    //   create: (context) => CompanyBloc(ApiClient.instance),
    //   child: const ProfilePage(),
    // ),
    ProfilePage(),
  ];

  //
  void _onPageChanged(int index) {
    if (index == 2) {
      return;
    }
    setState(() {
      _selectedIndex = index;
    });
  }

  void _onItemTapped(int index) {
    // AI 按钮的索引是 2
    // if (index == 2) {
    //   GoRouter.of(context).push('/ai');
    //   // showConfirmationDialog(
    //   //   context,
    //   //   companyName: 'XXXXXXXXXXXX公司',
    //   //   serviceName: "title",
    //   //   amount: "100 /yue",
    //   // );
    // } else {
    //   // 其他按钮正常切换页面
    //   _pageController.jumpToPage(index > 2 ? index - 1 : index);
    // }

    if (index != 2) {
      // 只有非中间按钮才更新选中状态
      // setState(() {
      //   _selectedIndex = index;
      // });
      _pageController.jumpToPage(index > 2 ? index - 1 : index);
    } else {
      context.read<ServiceBloc>().add(ServiceCheckChatEvent());
      // GoRouter.of(context).push('/ai');
    }
  }

  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 5);
    AuthService().authStatusStream.listen((status) {
      switch (status) {
        case AuthStatus.reLoginRequired:
          break;
        case AuthStatus.loggedIn:
          // 处理登录成功
          break;
        case AuthStatus.loggedOut:
          // 处理登出
          break;
        case AuthStatus.GoTHree:
          setState(() {
            _selectedIndex = 3;
          });
          lastIndex = 3;
          _pageController.jumpToPage(2);
          _tabController.animateTo(3);
          break;
      }
    });
  }

  final bool _canScroll = false;

  @override
  Widget build(BuildContext context) {
    print("build    Home Page ");
    return Scaffold(
      body: BlocListener<ServiceBloc, ServiceState>(
        listener: (context, state) {
          if (state is ServiceCanChatState) {
            GoRouter.of(context).push('/ai');
          } else if (state is ServiceChatErrorState) {
            EasyLoading.showToast(state.message);
          }
        },
        child: BlocListener<HomeBloc, HomeState>(
          listener: (context, state) {
            if (state is HomeLoading) {
            } else if (state is HomeLoadSuccess) {
            } else if (state is HomeLoadFailure) {}
          },
          child: PageView(
            physics: _canScroll
                ? AlwaysScrollableScrollPhysics()
                : NeverScrollableScrollPhysics(),
            controller: _pageController,
            onPageChanged: _onPageChanged,
            children: _pages,
          ),
        ),
      ),
      bottomNavigationBar: ConvexAppBar.builder(
        count: 5,
        // 选项卡数量
        top: -10,
        // 控制凸起的垂直位置
        curve: Curves.easeInCubic,
        // 控制凸起的动画曲线
        curveSize: 50,
        height: 50,
        // 添加这一行来控制整体高度
        controller: _tabController,
        itemBuilder: CustomConvexDelegate(
          items: [
            TabItem(
              icon: Image.asset(Assets.iconIconHomeMain),
              activeIcon: Image.asset(Assets.iconIconHomeMainsel),
              title: "首页",
            ),
            TabItem(
              icon: Image.asset(Assets.iconIconHomeBill),
              activeIcon: Image.asset(Assets.iconIconHomeBillsel),
              title: "报表",
            ),
            TabItem(icon: Image.asset(Assets.iconIconHomeAi), title: null),
            TabItem(
              icon: Image.asset(Assets.iconIconHomeService),
              activeIcon: Image.asset(Assets.iconIconHomeServicesel),
              title: "设置",
            ),
            TabItem(
              icon: Image.asset(Assets.iconIconHomeMine),
              activeIcon: Image.asset(Assets.iconIconHomeMinesel),
              title: "我的",
            ),
          ],
          color: Color(0xFF7A7A7A), // 未选中颜色
          activeColor: Color(0xFF41C7DD), // 选中颜色
        ),
        initialActiveIndex: _selectedIndex,
        onTap: (int index) {
          // 处理选项卡点击事件
          if (index == 2) {
            // context.read<ServiceBloc>().add(ServiceCheckChatEvent());
            GoRouter.of(context).push('/ai');
            // setState(() {
            //   _selectedIndex = lastIndex;
            // });
            // 只有非中间按钮才更新选中状态
            _tabController.animateTo(lastIndex);
          } else {
            lastIndex = index;
            setState(() {
              _selectedIndex = index;
            });
            _tabController.animateTo(index);
            _pageController.jumpToPage(index > 2 ? index - 1 : index);
          }
        },
        backgroundColor: Colors.white,
      ),
    );

    // return Scaffold(
    //   body: PageView(
    //     // controller: _pageController,
    //     // onPageChanged: _onPageChanged,
    //     children: _pages,
    //   ),
    //   bottomNavigationBar: ConvexAppBar(
    //     style: TabStyle.fixedCircle,
    //     backgroundColor: Colors.white,
    //     color: Colors.grey[600],
    //     activeColor: const Color(0xFF007AFF),
    //     elevation: 2.0,
    //     items: const [
    //       TabItem(icon: Icons.home_rounded, title: '首页'),
    //       TabItem(icon: Icons.article_outlined, title: '报表'),
    //       TabItem(icon: Icons.blur_on, title: 'AI'),
    //       TabItem(icon: Icons.support_agent_rounded, title: '服务'),
    //       TabItem(icon: Icons.person_outline_rounded, title: '我的'),
    //     ],
    //     // 关键：将AI按钮的点击事件和其他按钮区分开
    //     onTap: _onItemTapped,
    //     // 关键：让PageView的索引和导航栏的选中状态同步
    //     initialActiveIndex:  _selectedIndex == 2 ? 0 : _selectedIndex,
    //   ),
    // );
  }
}
